package com.example.musicapi.controller;


import com.example.musicapi.entity.News;
import com.example.musicapi.entity.User;
import com.example.musicapi.service.NewsService;
import com.example.musicapi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.List;

@RestController
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private NewsService newsService;

    @PostMapping("/get")
    @ResponseBody
    public List<News> getAll(@RequestParam(defaultValue = "0") int page,
                             @RequestParam(defaultValue = "100") int size,
                             @RequestParam(required = false) String key) {
        if(key!=null && !key.equals("")){
            return newsService.search(page, size,key);
        }else{
            return newsService.findAll(page, size);
        }

    }

    @PostMapping("/getOne")
    @ResponseBody
    public News get(@RequestParam String id){
        return newsService.findById(id) ;
    }


    @PostMapping("/add")
    public String add(String author, String title, String txt,
                      String time,@RequestParam(required = false) String avatarBase64 ) {
        News u=new News();
        if(avatarBase64!=null && !avatarBase64.equals("")){
            byte[] avatarBytes = Base64.getDecoder().decode(avatarBase64);
            u=new News(null,author,title,txt,time,avatarBytes);
        }else{
            return "fail";
        }
        u=newsService.add(u);
        if(u!=null && u.getId()!=null)
            return "success";
        else{
            return "fail";
        }

    }


    @PostMapping("/delete")
    public String delete(String id) {
        try {
            newsService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "success";
    }
}
